package com.lihuanyu.upcOA.service;

import com.lihuanyu.upcOA.conn.databaseUtil;
import com.lihuanyu.upcOA.model.userTable;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created by skyADMIN on 15/8/29.
 */
public class check {
    private Connection conn;
    private PreparedStatement pstmt;
    public void closeSql(PreparedStatement pstmt,Connection conn) throws SQLException {
        pstmt.close();
        conn.close();
    }
    public int checkUser(userTable user){
        conn = new databaseUtil().getCon();
        String role = user.getRole();
        //System.out.print(role);
        if (role.equals("student")){
            try{
                pstmt=conn.prepareStatement("SELECT * FROM student_login WHERE username=? and password=?");
                pstmt.setString(1,user.getUsername());
                pstmt.setString(2,user.getPassword());
                ResultSet rs = pstmt.executeQuery();
                if (rs.next()){
                    user.setUid(rs.getInt(1));
                    closeSql(pstmt,conn);
                    return 1;
                }else {
                    closeSql(pstmt,conn);
                    return 0;
                }
            }catch (SQLException e){
                e.printStackTrace();
                return 0;
            }
        }else {
            try {
                pstmt=conn.prepareStatement("SELECT * FROM teacher_login WHERE username=? and password=?");
                pstmt.setString(1,user.getUsername());
                pstmt.setString(2,user.getPassword());
                ResultSet rs = pstmt.executeQuery();
                if (rs.next()){
                    user.setUid(rs.getInt(1));
                    closeSql(pstmt,conn);
                    return 2;
                }else {
                    closeSql(pstmt,conn);
                    return 0;
                }
            }catch (SQLException e){
                e.printStackTrace();
                return 0;
            }
        }
    }
}
